package com.ma.workorder;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.view.View;

import com.ma.R;

import com.ma.databinding.ActivityRepairBinding;
import com.ma.workorder.audioManager.MediaManager;
import com.ma.workorder.contacts.ChooseDepartActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionYes;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import base.BaseActivity;

import bean.LoginBean;
import database.dao.DBManager;
import database.table.Bsgz;
import database.table.Gdb;
import httpUtil.Api;
import httpUtil.CacheManager;
import httpUtil.Http;
import lomasky.xui.ImgSelectDialog;
import utils.CameraUtil;
import utils.ConstantUtil;
import utils.FileUtils;
import utils.JsonUtil;
import utils.SharedPrefUtil;
import utils.StringUtil;
import utils.UUIDUtil;

public class RepairActivity extends BaseActivity {
    Bsgz bsgz = new Bsgz();
    ActivityRepairBinding binding;
    LoginBean loginBean;
    Gdb bean = new Gdb();
    ImgSelectDialog imgSelectDialog ;
    List<String> imgs= new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loginBean = (LoginBean) getIntent().getSerializableExtra(ConstantUtil.DATA1);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_repair);
        bean.setGDB_YYSJ(StringUtil.formatTime(new Date()));
        bean.setGDB_FQR(loginBean.getRealName());
        bean.setGDB_FQRWJ(loginBean.getID());
        bean.setZYX(true);
        bean.setNWBSJ(true);
        bean.setJJX(true);
        bean.setGQYZ(true);
        bean.setXMBS(SharedPrefUtil.getInstance().getInt(ConstantUtil.XMBS));
        binding.setGdb(bean);
        binding.img.setList(imgs);
        binding.img.setOnItemClickListener((adapterView, view, i, l) -> {
            if (binding.img.getList().size() > 2) {
                showDialog("只能上传两张图，请先在相册中移除一张");
                return;

            }

            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.setSingleChoiceItems(new CharSequence[]{"拍照", "相册"},-1,(dialogInterface, i1) -> {

                if (i1==0){
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        AndPermission.with(this)
                                .requestCode(ConstantUtil.permission_code_cam)
                                .permission(Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
                                .send();

                    } else {
                        openCam();
                    }
                }else {
                    showImgs();
                }




                dialogInterface.dismiss();

            });


            builder.show();





        });

        getType();


    }

    public void showImgs() {

        if (imgSelectDialog == null) {
            imgSelectDialog = new ImgSelectDialog(this);
            imgSelectDialog.setMaxCount(3);
            imgSelectDialog.setSelectedList(binding.img.getList());
            imgSelectDialog.setSelectedLisenter(list -> {
                binding.img.setList(list);
            });
        }

        imgSelectDialog.show();

    }


    @Override
    protected void onPause() {
        MediaManager.release();//保证在退出该页面时，终止语音播放
        super.onPause();
    }

    public void yes(View view) {
        showCustomDialog("确定保存", "是否保存", view1 -> {

//            Http.postFormWithJson(Api.AddGDB, "data", bean, new HashMap<>())
//                    .subscribe(res -> {
//                        finish();
//                    });
            bean.setGDB_GDH(StringUtil.formatTime(new Date()).replace("/","").replace(" ","").replace(":",""));
            bean.setGDB_ZJ(UUIDUtil.uuid());
            imgs=binding.img.getList();
            for (int i = 0; i < imgs.size(); i++) {
                if (i==0){
                    bean.setmTp1(imgs.get(i));
                }else if(i==1){
                    bean.setmTp2(imgs.get(i));
                }else if(i==2){
                    bean.setmTp3(imgs.get(i));
                }
            }

            DBManager.get().getGdbDao().insert(bean);
            finish();





        }, view1 -> {

        });

    }

    public void no(View view) {
        showCustomDialog("确定放弃", "是否放弃", view1 -> {
            finish();
        }, view1 -> {

        });

    }

    public void select_address(View view) {

    }

    public void select_type(View view) {
        showTypeDialog();

    }

    List<database.table.Bsgz> Bsgzs = new ArrayList<>();

    public void getType() {

        Bsgzs = DBManager.get().getBsgzDao().loadAll();
//        Map<String, Object> map = new HashMap<>();
//        map.put("YH_ZJ", "78A4796EC69E4E4DB08FD0C0EE9A154C");
//        map.put("XMBS", "233");
//        showProgressDialog();
//        Http.post(Api.GetBSGZ, map).subscribe(
//                res -> {
//                    Bsgzs = JsonUtil.getList(res.getContent().toString(), Bsgz.class);
//                    closeProgressDialog();
//
//                }, throwable -> {
//                    closeProgressDialog();
//                    log(throwable.getLocalizedMessage());
//                }
//
//
//        );

    }

    public void showTypeDialog() {


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        String[] strings = new String[Bsgzs.size()];
        for (int i = 0; i < Bsgzs.size(); i++) {
            strings[i] = Bsgzs.get(i).getBSGZ_GZMC();
        }

        builder.setSingleChoiceItems(strings, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                bsgz = Bsgzs.get(i);
                bean.setGDB_GZLX(bsgz.getBSGZ_GZMC());
                bean.setGDB_GZLXWJ(bsgz.getBSGZ_ZJ());
                bean.setGDB_WCBM(bsgz.getBSGZ_SSGWMC());
                bean.setGDB_WCSX(bsgz.getBSGZ_WCSX());
                bean.setGDB_WCSXDW(bsgz.getBSGZ_WCSXDW());
                binding.setGdb(bean);

                dialogInterface.dismiss();


            }
        });

        builder.show();


    }

    public void select_time_unit(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setSingleChoiceItems(R.array.ymd, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                bsgz.setBSGZ_WCSXDW(getResources().getStringArray(R.array.ymd)[i]);
                bean.setGDB_WCSXDW(bsgz.getBSGZ_WCSXDW());
                binding.setGdb(bean);
                dialogInterface.dismiss();

            }
        });

        builder.show();
    }

    public void select_depart(View view) {

        Intent intent = new Intent(this, ChooseDepartActivity.class);
        intent.putExtra(ConstantUtil.DATA1,loginBean);
        startActivity(intent);

    }




    private Uri uri;

    public void openAudio(View view) {


        boolean isWriteFile = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
        boolean isAudio = ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED;
        if (isWriteFile || isAudio) {
            AndPermission.with(this)
                    .requestCode(ConstantUtil.permission_code_audio)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)
                    .send();
        } else {
            Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
            startActivityForResult(intent, ConstantUtil.permission_code_audio);
        }

    }

    //6.0
    @PermissionYes(ConstantUtil.permission_code_audio)
    private void permissionYes() {
        Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        startActivityForResult(intent, ConstantUtil.permission_code_audio);

    }

    java.io.File picName;

    public void openCam() {
        picName = CameraUtil.createImgToAlbum();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile( picName));
        startActivityForResult(intent, ConstantUtil.permission_code_cam);
    }

    @PermissionYes(ConstantUtil.permission_code_store)
    private void permissionStoreYes() {
        showImgs();
    }

    @PermissionYes(ConstantUtil.permission_code_cam)
    private void permissionCamYes() {
        openCam();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == ConstantUtil.permission_code_cam) {
                CameraUtil.toAlbum(this, picName);
                List<String> list = binding.img.getList();
                list.add(picName.getPath());
                binding.img.setList(list);


            }else {
                uri = data.getData();

                String   f= FileUtils.getFilePath(this,uri) ;
                toast(f );
                bean.setmYYWJ(f);
            }
        }

    }

    public void getDepart() {
        Map<String,Object> map= new HashMap<>();
        map.put("ID",loginBean.getID());
        Http.post(Api.GetBMJGTree,map).subscribe(res -> {

        });
    }

}
